package tech.yangzhijie.blog.admin.config.authentication;

import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 过滤放行的路径
 * @Author: 探险家劫
 * @Date: 2021/11/22 21:11
 */
public class AuthorizationFilter extends GenericFilterBean {

    private List<Pattern> patterns = new ArrayList<>();

    private Map<String, String> excludeMap;

    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        if (excludeMap == null || excludeMap.isEmpty()) {
            return;
        }
        String excludes = excludeMap.get("exclude");
        String[] excludeArr = excludes.split(",");
        for (int i = 0; i < excludeArr.length; i++) {
            String exclude = excludeArr[i];
            if (exclude == null || exclude.isEmpty()) continue;
            if (exclude.contains("/**")) {
                exclude = exclude.replaceAll("[*]", "");
                String regex = "(" + exclude.substring(0, exclude.length() - 1) + "|" + exclude + "([a-zA-Z0-9_]+/?)*)";
                patterns.add(Pattern.compile(regex));
            } else if (exclude.contains("/*")) {
                exclude = exclude.replaceAll("[*]", "");
                String regex = "(" + exclude.substring(0, exclude.length() - 1) + "|" + exclude + "[a-zA-Z0-9_]+/?)";
                patterns.add(Pattern.compile(regex));
            } else {
                patterns.add(Pattern.compile(exclude));
            }
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    }

    /**
     * true     排除
     * false    不排除
     */
    private boolean ifExclude(String uri) {
        return patterns.stream().anyMatch(pattern -> pattern.matcher(uri).matches());
    }
}
